package org.kernely.ui.settings;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.kernely.security.dao.UserDAO;
import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.User;
import org.kernely.ui.MainApplication;
import org.kernely.ui.mvp.KernelyPresenter;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Window.Notification;

public class KernelySettingsPresenter extends KernelyPresenter<KernelySettingsView> {

	/**
	 * @see KernelyPresenter#bind()
	 */
	@Override
	public final void bind() {
		this.view.getSavePasswordButton().addListener(new ClickListener(){

			@Override
			public void buttonClick(ClickEvent event) {
				savePasswordProcess();
			}

		});
	}


	final private void savePasswordProcess() {

		// We check the validity of user's inputs
		try {
			User u = MainApplication.getSecurityService().getCurrentUser();
			UserDAO udao = new UserDAO();
			UserDetailsDAO uddao = new UserDetailsDAO();

			//Check if the fields are empty or not
			view.getOldPasswordField().validate();
			view.getNewPasswordField().validate();
			view.getConfirmPasswordField().validate();

			//Check the new and confirm password are the same
			if (! view.getNewPasswordField().toString().equals(view.getConfirmPasswordField().toString())){
				throw new InvalidValueException("You have entered different password in the New and Confirm fields.");
			}

			//Check if the user entered the valid old password
			String password = (new Sha256Hash(view.getOldPasswordField().getValue().toString())).toString();
			String userPassword = u.getPassword();
			if (userPassword.equals(password)){
				u.setPassword((new Sha256Hash(view.getNewPasswordField().getValue().toString())).toString());
				udao.update(u);
			} else {				
				throw new InvalidValueException("You entered a wrong password.");
			}
			view.getWindow().showNotification(new KernelyNotification("Password successfully changed.", KernelyNotification.INFO_ICON));
		}
		catch (InvalidValueException e){
			//Log the failure on screen, to give feedback to the user
			KernelyNotification n = new KernelyNotification(e.getMessage(), KernelyNotification.ERROR_ICON);
			view.getWindow().showNotification(n);
		}
	}
}
